M=require("ming_node")
BaseMapper=require("ming_node/module/BaseMapper")
Db=M.getMySql({database:"miapi"})
app=M.server();



app.listen(8888)

const lottery_number_mapper=new BaseMapper("lottery_number");
const user_mapper=new BaseMapper("t_user");
async function genereteLottery_number(){
    let r=await   lottery_number_mapper.selectList({
        queryCase:"isuse=0",
        limit :1,
        order:"id desc"
    })
    if(r.length==0){
        return -1;
    }
    r[0].isuse=1;
    await  lottery_number_mapper.update(r[0])
    return    r[0].lottery_number;
}

stage=[]


lock=0;

app.get("/generateNum",async (req,res)=>{
    if(lock==1){
        res.send(M.failResult("fail lock"));
        return;
    }
    lock=1;
   let name=req.params.name;
   let count=await user_mapper.selectCount({queryCase:`name='${name}'`})
    if(count>0){
        lock=0;
        res.send(M.failResult("fail"));
        return;
    }
    let num= await genereteLottery_number();
    if(num==-1){
        lock=0;
        res.send(M.failResult("fail no data"));
        return;
    }
    await user_mapper.insert({
        name:name,
        lottery_number:num,
    });
    lock=0;
    res.send(M.successResult(num))
})


app.get("/stage",async (req,res)=>{
    res.send(M.successResult(stage))
})